//
//  ST_SinglePeculiarityWaterfallController.swift
//  btvideo
//
//  Created by mac on 2020/2/27.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import HandyJSON
import SwiftyUserDefaults
import MJRefresh

enum ST_SinglePeculiarityWaterfallStyle {
    case normal,loveOperation,me
}


//9_个人中心_我喜欢的特质详情 - 蓝湖
class ST_SinglePeculiarityWaterfallController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white

        view.addSubview(own_navigation_bar)
        own_navigation_bar.snp.makeConstraints { (make) in
            make.right.left.top.equalTo(view)
            make.height.equalTo(statusBarHeight+44)
        }
        view.addSubview(left_nav_btn)
        own_navigation_bar.addSubview(title_nav_btn)
        
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(8)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_nav_btn)
            make.centerX.equalTo(own_navigation_bar)
        }

         
        
        view.insertSubview(collectionView, belowSubview: own_navigation_bar)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        request_data()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.my_pairs_user_info_updated, object: nil)
          
        NotificationCenter.default.addObserver(self, selector: #selector(thumb_up_noti_handle(noti:)), name: Notification.Name.thumbUp, object: nil)
                
    }
    
    
    @objc fileprivate func thumb_up_noti_handle(noti:Notification){
        
        
//        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController,vc != self else{
            return
        }
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool else{
            return
        }
        
        guard let idx = data_array.firstIndex(where: {$0.group_id.string == id}) else{
            return
        }
            
        let index = Int(idx.uInt)
        
        data_array[safe: index]?.isThumbUp = isThumbUp
        
        if isThumbUp{
            data_array[safe: index]?.thumbUpCount += 1
        }else{
            data_array[safe: index]?.thumbUpCount -= 1
        }
        
        self.collectionView.performBatchUpdates({
            
            self.collectionView.reloadItems(at: [IndexPath.init(row: index, section: 0)])
            
        }) { (f) in
            
        }
            
    }
    deinit {
//        print("特质展示单人单特质 开始 释放")
        NotificationCenter.default.removeObserver(self)
    }
    
//    MARK: - require assign
    var userID = ""
    var peculiarity_id = ""
    
    var type = ST_SinglePeculiarityWaterfallStyle.normal
    
    
//    MARK: - Properties

    
    fileprivate lazy var own_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var left_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("特质_icon_返回"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        
//        control.backgroundColor = Color.random
        
        control.addTarget(self, action: #selector(left_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(Color.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        
        control.addTarget(self, action: #selector(title_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
       
    
    
    fileprivate lazy var transition = ST_PairsTransition()
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
       let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = ST_PinterestHomeCellMinimumColumnSpacing
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 10, bottom: 0, right: 10)
        return controlLayout
    }()
    
    fileprivate lazy var sectionheader_height:CGFloat = {
        
        switch type {
            
        case .loveOperation,.me:
            
            return 295
        default:
            return  240
        }
        
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: ST_TraitOfOperatCell.self)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom, right: 0)
        
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_SinglePeculiarityDetialBaseSupplementView.self)
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: SingleOtherPeculiaritySupplementView.self)
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: SingleEditPeculiaritySupplementView.self)
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_RecommendPeculiaritySupplementView.self)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    //    MARK: SetUp Data
    fileprivate lazy var data_array = [ST_TraitOfOperatCellModel]()
    
    /**
     推荐特质
     */
    fileprivate lazy var recommend_array = [ST_TraitOfOperatCellModel]()
    
    fileprivate var headerModel:SinglePrcDetialModel?
    
    fileprivate var currentPage = 0
    
    @objc fileprivate func refresh_data(){
        
        if self.userID != Defaults[.currentUserID]{
            return
        }
        
        currentPage = 0
        
        request_data()
    }
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,"feature_id":peculiarity_id,"target_accid":userID] as [String : Any]
        
        
        print("bug 2303:",param)
        
        JVrequest(PH.userPeculiarityDetailApi,parameters:param, success: { (json) in
            
            self.hidden_indeterminate_h_u_d()
            
            print("单人特质数据：",json["data"])
            
            let data = json["data"]
            
            self.headerModel = SinglePrcDetialModel.deserialize(from: data.dictionaryObject)
             
            self.headerModel?.total = data["list"]["total"].intValue
            
            self.headerModel?.information?.accid = self.userID
            
            self.title_nav_btn.setTitleForAllStates(self.headerModel?.feature_detail?.name ?? "")
            
            var dataCount = 0
            if let array = [ST_SingleHumanST_PeculiarityCellModel].deserialize(from: data["list"]["data"].arrayObject) as? [ST_SingleHumanST_PeculiarityCellModel]{
                
                dataCount = array.count
                
                let list = array.map({ (item) -> ST_TraitOfOperatCellModel in
                    
                    if self.userID == Defaults[.currentUserID]{
                        item.is_thumb_up = true
                    }
                    return item.convert_to_trait_cell_model(userID: self.userID, peculiarity_id: self.peculiarity_id.int ?? 0)
                })
                
                if self.currentPage == 1{
                    self.data_array = list
                }else{
                    self.data_array += list
                }
            }
            
                
            self.collectionView.reloadData {
//                直接加载推荐列表，所以等，推荐列表加载完成后 在播放视频就行啦
                if self.currentPage == 1 && dataCount < 20{
                    return
                }
                
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
                
            
            self.load_more_option_style(tableView: self.collectionView, count: dataCount, pageSize: 20) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                    self?.request_data()
                })
            }
      
//            没有更多数据了  推荐特质请求
            if dataCount < 20{
                self.request_recommend_data()
            }
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
        
    }
    
    
    
    fileprivate var current_recommend_page = 0
    
    fileprivate func request_recommend_data(){
        
        
        current_recommend_page += 1
        
        let param = ["page":current_recommend_page,"feature_id":peculiarity_id,"target_accid":userID] as [String : Any]
        
        JVrequest(PH.RecommendPeculiarityApi,parameters: param, success: { (json) in
            
            print("推荐特质:",json)
            
            let list = json["data"].arrayValue
                        
            let aArray = list.map { (itemJson) -> ST_TraitOfOperatCellModel in
                let m = ST_TraitOfOperatCellModel.init(json: itemJson)
                m.create_view_model_set(maxContentHeight: ST_ShowTraitCell.two_line_max_height)
                return m
            }
            
            if self.current_recommend_page == 1{
                self.recommend_array = aArray
            }else{
                self.recommend_array += aArray
            }
            
            self.load_more_option_style(tableView: self.collectionView, count: aArray.count, pageSize: 20) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_recommend_data()
                })
            }
            
            self.pause_video()
            self.collectionView.reloadData {
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
            
            
            
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
        
    }
    
    //    MARK:- Player View
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 20
        return control
    }()
    

//    MARK:- Play Operation
    fileprivate var current_play_index_path:IndexPath?
    
                                                        
    fileprivate func play(indexPath:IndexPath){
            
        pause_video()
        
        if TopmostViewController() != self{
            return
        }
        
        
        guard let cell = collectionView.cellForItem(at: indexPath) as? ST_ShowTraitCell , let dataItem = data_array[safe:indexPath.item] else{return}
        
        
        
        if dataItem.type != 1{
            
            return
        }
            
        cell.contentView.addSubview(playerView)
        
        let rect = cell.picutreframe_in_content_view()
         
        playerView.frame = rect
        
        let currModel = ST_PairsShareParticularModel.init(imageUrl: dataItem.imageUrl, videoUrl: dataItem.videoUrl, width: dataItem.width, height: dataItem.height)
        
        playerView.setUp(data_array: [currModel])
        
        current_play_index_path = indexPath
    }
    
    fileprivate func pause_video(){
        
        if playerView.frame.width == ScreenWidth{
            return
        }
        playerView.clear_data()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
        
        current_play_index_path = nil
    }
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
    
    /**
     找出可以播放的indexPath
     */
    fileprivate func find_can_play_index_path(determineContinueBlock:((UICollectionViewCell)->(Bool)))->IndexPath?{
        
        var foundIndex:IndexPath?
        
        for item in collectionView.visibleCells {
            
            if determineContinueBlock(item){
                continue
            }
            
            if let cell = item as? ST_ShowTraitCell,cell.model.type == .video{
                
                if let playIdx = collectionView.indexPath(for: cell){

                 if let last = foundIndex,last.item < playIdx.item{
                     continue
                 }
                    
                let rectInScreen = collectionView.convert(cell.frame, to: nil)
                            
                let intersect = containerRect.intersection(rectInScreen)
                
                let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
                //               小于 70% 换下一个哈
                if percent < 0.8{
                    continue
                }
                
               foundIndex = playIdx
                }
            }
        }
        
        return foundIndex
    }
    
    /**
     确定播放下一个indexPath
     */
    fileprivate func determined_will_play_index_path()->IndexPath?{
        
        var foundIndex:IndexPath?
        
//        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let currCell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(currCell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
//               大于 50% 还是展示自己
            if percent > 0.5{
                return curr
            }else{
                foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                    return item == currCell
                })
            }
        }else{
            
                // 取出第一个 video cell 播放
            foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                return false
            })
        }
        
//        print("Bug 10000-将要切换到另外一个Item :",foundIndex)
        
        return foundIndex
    }
    

}


extension ST_SinglePeculiarityWaterfallController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if recommend_array.count < 1{
            return 1
        }else{
            return 2
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if indexPath.section == 0{
            return data_array[safe:indexPath.item]?.size ?? CGSize.zero
        }else{
            return recommend_array[safe:indexPath.item]?.size ?? CGSize.zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if section == 0{
            return data_array.count
        }else{
            return recommend_array.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        if indexPath.section == 0{
            
            let cell = collectionView.dequeueReusableCell(withClass: ST_TraitOfOperatCell.self, for: indexPath)
            
            cell.max_content_number_of_lines = 2
            
            if let m = data_array[safe:indexPath.item]{
                cell.model = m
            }
            cell.comment_btn.alpha = 0
            
            return cell
            
        }else{
            
            
            let cell = collectionView.dequeueReusableCell(withClass: ST_TraitOfOperatCell.self, for: indexPath)
            
            cell.max_content_number_of_lines = 0
            
            if let m = recommend_array[safe:indexPath.item]{
                cell.model = m
            }
            
            cell.refresh_water_fall_closure = {[weak self] in
                
                self?.show_indeterminate_h_u_d()
                
                self?.refresh_data()
                
            }
            
            return cell
            
        }
        
        
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
                
            guard let currCell = collectionView.cellForItem(at: indexPath),let objCell = currCell as? ST_PecGroupshareViewRectProtocol else{
                    return
                }
        
            var recommendModel:ST_ShowTraitCellModel?
        
            var currModel:ST_PairsShareParticularModel?
            
            if indexPath.section == 0{
                recommendModel = data_array[safe:indexPath.row]
            }else{
                recommendModel = recommend_array[safe:indexPath.row]
            }
        
//              当前正在播放 并且不是当前点击这个
            if current_play_index_path != indexPath{
                    
                    pause_video()
                    
                  if let model = recommendModel{
//                        1视频 2 图片
                    if model.type == .video{

                        currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, videoUrl: model.videoUrl, width: model.width, height: model.height)
                        
                        
                    }else{
                        
                        currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, width: model.width, height: model.height)

                    }
                }
                    
                    
                guard let curr = currModel else{ return}
                    
                playerView.setUp(data_array: [curr])
                    
            }
        
                transition.operationView = self.playerView
                
                let rectInScreen = currCell.convert(objCell.picutreframe_in_content_view(), to: nil)
                
                playerView.present_start_rect = rectInScreen
                playerView.present_start_idx = indexPath
                playerView.fromeController = self
             
        if let item = recommendModel{
            
            ST_InteractiveST_PeculiarityGroupViewController.present_interactive_peculiarity_group_controller(accid: item.accid, groupId: item.group_id.string, peculiarity_id: item.feature_id.string, remark: item.sign, firstPhotoSize: CGSize.init(width: item.width, height: item.height), transition: transition, presentRootController: self)
            
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForHeaderIn section: Int) -> CGFloat {
        if section == 0{
            return sectionheader_height
        }else{
            return 72
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if indexPath.section == 1{
            
            let reuseView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_RecommendPeculiaritySupplementView.self, for: indexPath)
            
            return reuseView
        }
        
        
        var reuseView:ST_SinglePeculiarityDetialBaseSupplementView!
        
        switch type {
            
        case .loveOperation:
            
            reuseView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: SingleOtherPeculiaritySupplementView.self, for: indexPath)
            
        case .me:
            
            reuseView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: SingleEditPeculiaritySupplementView.self, for: indexPath)
            
        default:
            
            reuseView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_SinglePeculiarityDetialBaseSupplementView.self, for: indexPath)
        }
        
        reuseView.dataModel = headerModel
        
        
        if headerModel?.information == nil{
            reuseView.isHidden = true
        }else{
            reuseView.isHidden = false
        }
        
        return reuseView
    }
    
//    MARK: Scroll Delegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let y = scrollView.contentOffset.y
        
        let offSet = sectionheader_height - y
        
        if offSet < 0{
            
            own_navigation_bar.alpha = 1
            
        }else if offSet >= own_navigation_bar_show_coefficient{
            
            own_navigation_bar.alpha = 0
        }else{
            own_navigation_bar.alpha = 1-offSet/own_navigation_bar_show_coefficient
        }
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let cell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(cell.frame, to: nil)
            
            if containerRect.intersects(rectInScreen) == false{
                pause_video()
            }
        }
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
            scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
            scrollviewdidEndScroll(scrollView)
        
    }
    
//    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        guard let willPlayIdx = determined_will_play_index_path() else {
            
            pause_video()
            
            return
        }
        
        if let curr = current_play_index_path,curr.item == willPlayIdx.item{
            return
        }
        
        play(indexPath: willPlayIdx)
        
    }
    
}



extension ST_SinglePeculiarityWaterfallController:ST_PairsTransitionProtocol{
    
    
    func present_start_cell()->UICollectionViewCell?{
        
        guard let idx = playerView.present_start_idx  else {
            return nil
        }
        
        return self.collectionView.cellForItem(at: idx)
        
    }
    
}


//MARK: - Navigation Bar Event
extension ST_SinglePeculiarityWaterfallController{
    
    @objc func title_click(){
        
    }
    
    @objc func left_click(){
        
        self.goback_previous_controller()
    }
}

